package com.lry.basic.juc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/8/3
 */
public class TestReadWriteLock {
    Object data;
    volatile boolean cacheValid;
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    void processCachedData() {
      rwl.readLock().lock();
      if (!cacheValid) {//这里被改为flase后，只有读锁了
          //得到写锁之前必须释放读锁，不释放读锁，无法活得写锁
        rwl.readLock().unlock();
        rwl.writeLock().lock();
        try {
          if (!cacheValid) {//只有一个线程改数据
            data = 1;
            cacheValid = true;
          }
         // 写锁释放前获取读锁，这样才是降级
          rwl.readLock().lock();
        } finally {
          rwl.writeLock().unlock();
        }
      }
      try {
          System.out.println(data);
      } finally {
        rwl.readLock().unlock();
      }

    }
}

